package ylg.com.cn.youtube.main.fragment_home;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import ylg.com.cn.youtube.R;
import ylg.com.cn.youtube._commons.decorators.MDividerDecorationNoTop;
import ylg.com.cn.youtube._data.Video;
import ylg.com.cn.youtube._data.Video1;
import ylg.com.cn.youtube._data.constants.Constants;

/**
 * Created by MyPC on 2017/1/11.
 */
public class HomePageFragment extends Fragment implements HomePageContract.View {

    private int[] imgearry = new int[]{
            R.mipmap.cover1,R.mipmap.cover2,R.mipmap.cover3,R.mipmap.cover4,R.mipmap.cover5,R.mipmap.cover6,R.mipmap.cover7
    };
    // Presenter
    HomePageContract.Presenter presenter;
    private OnFragmentInteractionListener mListener;
    private RecyclerViewAdapter adapter;
    private LinearLayoutManager mLayoutManager;

    private boolean isLoading = false;

    public HomePageFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static HomePageFragment newInstance() {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_page, container, false);
    }

    SwipeRefreshLayout swipetorefresh;
    RecyclerView recyclerView;
    ProgressBar pb;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getViews(view);
        List<Video1> list = new ArrayList<>();
        for (int i  = 0 ;i<imgearry.length;i++){
            Video1 video1 = new Video1();
            //  Drawable dhome = ContextCompat.getDrawable(getContext(), imgearry[i]);
            video1.setImg_id(imgearry[i]);
            list.add(video1);
        }
        initRecyclerview(list);
    }

    private void getViews(View view){
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        swipetorefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipetorefresh);
        pb = (ProgressBar) view.findViewById(R.id.frg_progressbar_circular);
    }
    @Override
    public void showVideoList(List<Video> videos) {

    }

    private void initData(){

    }

    private void initRecyclerview(final List<Video1> videos) {
        // 如果是第一次：adapter 里的数据为空
            adapter = new RecyclerViewAdapter(getContext(), videos);
            mLayoutManager = new WrapContentLinearLayoutManager(getContext());
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new MDividerDecorationNoTop(ContextCompat.getDrawable(getContext(), R.drawable.home_page_divider_drawable)));
            swipetorefresh.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

    }
    @Override
    public void appendVideosToList(List<Video> videos) {

    }

    @Override
    public void showEmptyVideoError() {

    }

    @Override
    public void showVideosLoadingOnGoing() {

    }

    @Override
    public void showVideosLoadingComplete() {

    }

    @Override
    public void setPresenter(Object presenter) {
        this.presenter = (HomePageContract.Presenter) presenter;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    class RecyclerViewAdapter  extends  RecyclerView.Adapter<RecyclerView.ViewHolder>{

        private final Context ctx;
        private final List<Video1> videos;
        private int sw;
        private int sh;
        private Drawable emptyCover;
        private boolean hasFooterLoader = true;
        public RecyclerViewAdapter(Context ctx, List<Video1> videos) {
            this.ctx = ctx;
            this.videos = videos;
            // screen size 16:9
            sw = ctx.getResources().getDisplayMetrics().widthPixels;
            // 减去图片的 margin
            sw -= 2 * getResources().getDimensionPixelSize(R.dimen.main_img_margin);
            sh = sw * 9 /16;
            // 初始化空白的cover
            emptyCover = ContextCompat.getDrawable(ctx, R.drawable.empty_cover_drawable);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                return new VideoItemViewHolder(LayoutInflater.from(ctx).inflate(R.layout.main_home_recycler_item, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder hold, int position) {
            if (hold instanceof VideoItemViewHolder && position < videos.size()) {
                VideoItemViewHolder holder = (VideoItemViewHolder) hold;
                final Video1 video = videos.get(position);
                Drawable dhome = ContextCompat.getDrawable(getContext(), video.getImg_id());
                // 设置图片大小
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) holder.ivcover.getLayoutParams();
                lp.width = sw;
                lp.height = sh;
                holder.ivcover.setLayoutParams(lp);
                // 解决网络图片错位的问题
                holder.ivcover.setImageDrawable(dhome);
                holder.ivUser.setImageDrawable(dhome);
                holder.ivcover.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mListener.playVideo(null,v);
                    }
                });

            }
        }

        @Override
        public int getItemCount() {
            return videos.size();
        }


        public class VideoItemViewHolder extends RecyclerView.ViewHolder {
            private final View mViews;
            public ImageView ivcover, ivUser;
            public TextView tvTitle;

            public VideoItemViewHolder(View itemView) {
                super(itemView);
                mViews = itemView;
                ivcover = (ImageView) itemView.findViewById(R.id.imageview_cover);
                ivUser = (ImageView) itemView.findViewById(R.id.iv_user);
                tvTitle = (TextView) itemView.findViewById(R.id.tvtitle);
            }

        }
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void playVideo(Video video, View v);
    }

    /* 由于 LinearLayoutManager中有一定的bug，需要自定义一下本对象*/
    public class WrapContentLinearLayoutManager extends LinearLayoutManager {
        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }
        //... constructor
        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                Log.e("probe", "meet a IOOBE in RecyclerView");
            }
        }
    }
}
